package org.ourgrid.broker.business.schedulerdata.executor;

import java.util.ArrayList;
import java.util.List;

import org.ourgrid.broker.business.dao.BrokerDAOFactory;
import org.ourgrid.broker.business.dao.WorkerDAO;
import org.ourgrid.broker.business.schedulerdata.SchedulerData;
import org.ourgrid.broker.response.UnwantWorkerResponseTO;
import org.ourgrid.common.internal.IResponseTO;
import org.ourgrid.common.internal.response.ReleaseResponseTO;
import org.ourgrid.common.spec.job.JobSpec;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class UnwantWorkerExecutor extends AbstractSchedulerDataExecutor {
	
	/**
	 * <UNWANT_WORKER peerID='String' workerID='String' requestID='long' jobID='int' requiredWorkers='int'
	 *          maxFails='int' maxReplicas='int'/>
	 */
	public List<IResponseTO> execute(SchedulerData command) {
		List<IResponseTO> responses = new ArrayList<IResponseTO>();
		
		Document logDocFile = super.getXMl(command.getXml());
		
		Element element = logDocFile.getDocumentElement();
		
		String pID = element.getAttribute("peerAddress");
		String wID = element.getAttribute("workerAddress");
		long requestID = Long.valueOf(element.getAttribute("requestID"));
		int jobID = Integer.valueOf(element.getAttribute("jobID"));
		int requiredWorkers = Integer.valueOf(element.getAttribute("requiredWorkers"));
		int maxFails = Integer.valueOf(element.getAttribute("maxFails"));
		int maxReplicas = Integer.valueOf(element.getAttribute("maxReplicas"));
		
		
		if (pID != null && wID != null) {
			JobSpec jobSpec = BrokerDAOFactory.getInstance().getJobDAO().getJobSpec(jobID);

			UnwantWorkerResponseTO unwantWorkerTO = new UnwantWorkerResponseTO();
			unwantWorkerTO.setJobID(jobID);
			unwantWorkerTO.setJobSpec(jobSpec);
			unwantWorkerTO.setMaxFails(maxFails);
			unwantWorkerTO.setMaxReplicas(maxReplicas);
			unwantWorkerTO.setPeerAddress(pID);
			unwantWorkerTO.setRequestID(requestID);
			unwantWorkerTO.setRequiredWorkers(requiredWorkers);
			
			unwantWorkerTO.setWorkerAddress(wID);
			
			WorkerDAO workerDAO = BrokerDAOFactory.getInstance().getWorkerDAO();
			
			String workerPublicKey = workerDAO.getWorkerPublicKey(wID);
			unwantWorkerTO.setWorkerPublicKey(workerPublicKey);
			
			responses.add(unwantWorkerTO);
			
			ReleaseResponseTO releaseTO = new ReleaseResponseTO();
			releaseTO.setStubAddress(wID);
			
			responses.add(releaseTO);
			
			workerDAO.removeWorker(wID);
		}	
		
		return responses;
	}
}
